import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Base64;

/**
 * @ClassName LoadCertificateExample
 * @Description TODO
 * @Author 赵雷棚
 * @Date 2024/6/26 15:03
 **/
public class LoadCertificateExample {
    public static void main(String[] args) {
        try {
            // 加载KeyStore文件
            KeyStore keyStore = KeyStore.getInstance("JKS");
            FileInputStream fileInputStream = new FileInputStream("mykeystore.jks");
            keyStore.load(fileInputStream, "zhaoleipeng123".toCharArray());

            // 获取别名为mycert的证书
            Certificate certificate = keyStore.getCertificate("mycert");
            if (certificate != null) {
                System.out.println("Certificate loaded: " + certificate);
            } else {
                System.out.println("Certificate not found.");
            }

            // 获取证书的私钥
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry("mycert", new KeyStore.PasswordProtection("zhaoleipeng123".toCharArray()));
            PrivateKey privateKey = privateKeyEntry.getPrivateKey();
            // 转换私钥为PEM格式的Base64编码字符串
            byte[] encoded = privateKey.getEncoded();
            String pemPrivateKey = "-----BEGIN PRIVATE KEY-----\n" +
                    Base64.getEncoder().encodeToString(encoded) +
                    "\n-----END PRIVATE KEY-----\n";

            // 打印PEM格式的私钥
            System.out.println(pemPrivateKey);

            System.out.println("------------------");
            System.out.println(privateKey);

            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
